#include "measure.h"
#include <string.h>

uint32_t get_us_count(void);

/**
 * @brief 时间测量模块初始化
 *
 * @param pm : 测量尺结构体
 */
void measure_init(measure_t *pm)
{
    memset(pm, 0, sizeof(measure_t));
#if MEASURE_USE_STATISTICS
    pm->min = 0xFFFFFFFF;
    pm->clear = 30000;
    pm->reset = 1;
#endif
    pm->inited = 1;
}
/**
 * @brief
 *
 * @param ch
 * @return int32_t
 */
int32_t measure_begin(measure_t *pm)
{
    if (pm->inited)
    {
        pm->begin = get_us_count();
        return 0;
    }
    else
    {
        measure_init(pm);
        pm->begin = get_us_count();
        return -2;
    }
}
/**
 * @brief
 *
 * @param ch
 * @return int32_t
 */
int32_t measure_end(measure_t *pm)
{
    if (pm->inited)
    {
        pm->end = get_us_count();
        pm->current = pm->end - pm->begin;
#if MEASURE_USE_STATISTICS
        if (pm->max < pm->current)
            pm->max = pm->current;
        if (pm->min > pm->current)
            pm->min = pm->current;
        if ((++pm->count >= pm->clear) && pm->reset)
        {
            pm->min = 0xFFFFFFFF;
            pm->max = 0;
            pm->count = 0;
        }
#endif
        return 0;
    }
    else
    {
        measure_init(pm);
        return -2;
    }
}

/**
 * @brief 测量执行间隔
 *
 * @param pm 测量结构体指针
 * @return int32_t
 */
int32_t measure_interval(measure_t *pm)
{
    if (pm->inited)
    {
        pm->end = get_us_count();
        pm->current = pm->end - pm->begin;
        pm->begin = pm->end;
#if MEASURE_USE_STATISTICS
        if (pm->max < pm->current)
            pm->max = pm->current;
        if (pm->min > pm->current)
            pm->min = pm->current;
        if ((++pm->count >= pm->clear) && pm->reset)
        {
            pm->min = 0xFFFFFFFF;
            pm->max = 0;
            pm->count = 0;
        }
#endif
        return 0;
    }
    else
    {
        measure_init(pm);
        pm->begin = get_us_count();
        return -1;
    }
}
